#include "udpServer.hpp"
#include "onlineUser.hpp"
#include <memory>
// #include <fstream>
// #include <unordered_map>
// #include <signal.h>

using namespace Server;

static void Usage(string proc)
{
    cerr << "\nUsage:\n\t" << proc << " local_port\n\n";
}

// 聊天室小demo(雏形)
OnlineUser onlineuser;

void routeMessage(int sockfd, string clientip, uint16_t clientport, string message)
{
    // 对 message 进行处理
    if (message == "online")
        onlineuser.addUser(clientip, clientport);
    if (message == "offline")
        onlineuser.delUser(clientip, clientport);

    if (onlineuser.isOnline(clientip, clientport) == true)
    {
        // 消息的路由(群发)
        onlineuser.broadcastMessage(sockfd, clientip, clientport, message);
    }
    else
    {
        struct sockaddr_in client;
        bzero(&client, sizeof(client));
        client.sin_family = AF_INET;
        client.sin_port = htons(clientport);
        client.sin_addr.s_addr = inet_addr(clientip.c_str());

        string response = "你还没有上线, 请先上线, 运行: online";

        sendto(sockfd, response.c_str(), response.size(), 0, (struct sockaddr *)&client, sizeof(client));
    }
}

// ./udpServer port
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    uint16_t port = atoi(argv[1]);

    std::unique_ptr<udpServer> usvr(new udpServer(routeMessage, port));

    usvr->initServer();
    usvr->start();

    return 0;
}
